/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import controller.WeatherManager;
import entity.Event;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import org.primefaces.json.JSONArray;
import org.primefaces.json.JSONException;
import org.primefaces.json.JSONObject;
import utility.Forecast;

/**
 *
 * @author xubuntu
 */

@ManagedBean
@SessionScoped
public class WeatherBean {

    @EJB
    private WeatherManager wtrMgr;
     
    private Date today;
    @ManagedProperty( value = "#{navigationBean}" )
    private NavigationBean navigationBean;

    
    public WeatherBean() {                                                                   
        today= new Date();
    }
    
    public List<Forecast> loadWeather(List<Forecast> weathers,List<Event> events ) throws JSONException, IOException{
        int presente;
        // se non ci sono eventi non ci sono meteo da caricare
        if(events!= null && events.isEmpty()==false){
            for(Event e: events){
                presente=0;
                // carico meteo solo per eventi outdoor
                if(e.getTypeIo()== 1){
                    // controllo che non ho gia aggiunto un meteo uguale
                    if(weathers != null && weathers.isEmpty()==false){
                        for(Forecast fo: weathers){
                            if((fo.getPlace().equalsIgnoreCase(e.getPlace()))&&(fo.getDates().getDate() == e.getDateStart().getDate())){
                                presente=1;
                                break;
                            }
                        }
                    }
                    if(presente==0){
                        String result = "";
                        String URL_OpenWeatherMap_weather ="http://api.openweathermap.org/data/2.5/forecast/daily?q="+e.getPlace()+"&cnt=10&mode=json";

                        try {
                            URL url_weather = new URL(URL_OpenWeatherMap_weather);

                            HttpURLConnection httpURLConnection = (HttpURLConnection) url_weather.openConnection();

                            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

                                InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
                                BufferedReader bufferedReader = new BufferedReader(inputStreamReader, 8192);
                                String line = null;
                                while((line = bufferedReader.readLine()) != null){
                                    result += line;
                                }

                                bufferedReader.close();

                                JSONObject jsonObject = new JSONObject(result);
                                String result_weather;
                                String meteo=null;
                                String meteoDescription=null;
                               

                                int i,temperatura=0,k=0;
                                
                               long differenzaGiornilong = e.getDateStart().getTime()-today.getTime();
                                int giorno = Math.round(differenzaGiornilong/86400000)+1;
                                // le API forniscono previsioni solo per 10 giorni
                                if((giorno <9)&&(giorno >=0)){
                                    JSONArray jsList = jsonObject.getJSONArray("list");
                                    String citta = jsonObject.getJSONObject("city").getString("name");
                                    meteo = jsList.getJSONObject((int)giorno).getJSONArray("weather").getJSONObject(0).getString("main");
                                    meteoDescription = jsList.getJSONObject((int)giorno).getJSONArray("weather").getJSONObject(0).getString("description");
                                    temperatura =(jsList.getJSONObject((int)giorno).getJSONObject("temp").getInt("day")-273);
                                    Forecast f = new Forecast(citta,meteo,e.getDateStart(),meteoDescription,String.valueOf(temperatura));
                                    weathers.add(f);
                                    
                                }
                            }
                            else{
                                
                                System.out.println("citta non trovata");
                                navigationBean.redirectToErrorMeteoPage();
                            }
                            
                        } catch (MalformedURLException ex) {
                            ex.printStackTrace();
                        }    
                    }
                }
                
               
            }
            
        }
        return weathers;
    }

    public List<Forecast> getAllBadWeathers( List<Forecast> weathers) {
        
        List<Forecast> badWeathers = new ArrayList<Forecast>();
        
        if(weathers!=null && weathers.isEmpty()==false){
            for(Forecast f: weathers){
                
                if(f.getMeteo().equalsIgnoreCase("rain")||(f.getMeteo().equalsIgnoreCase("snow"))||(f.getMeteo().equalsIgnoreCase("thunderstorm"))){
                    if(badWeathers.contains(f)==false){
                        badWeathers.add(f);
                        System.out.println("badWeathers: "+f.getPlace());
                    }
                }
            }
        }
        return badWeathers;
    }
    public String getImageWeather(String meteo){
        if(meteo.equalsIgnoreCase("clouds"))
            return wtrMgr.getImageWeather("cloud");
        if(meteo.equalsIgnoreCase("rain"))
           return wtrMgr.getImageWeather("showerrain");
        if(meteo.equalsIgnoreCase("mist"))
           return wtrMgr.getImageWeather("mist");
        if(meteo.equalsIgnoreCase("snow"))
           return wtrMgr.getImageWeather("snow");
        if(meteo.equalsIgnoreCase("clear"))
           return wtrMgr.getImageWeather("sunnyday");
        if(meteo.equalsIgnoreCase("thunderstorm"))
           return wtrMgr.getImageWeather("thunderstorm");   
        if(meteo.equalsIgnoreCase("Not available"))
           return wtrMgr.getImageWeather("unavailable"); 
        return wtrMgr.getImageWeather("rainday");
    }

    public Date searchSunny(Event e, int differenzaGiorni){
        int trovato,i;
        Date dataTrovata=new Date();
        System.out.println("Parte serachSunny");
        // calcolo della data massima delle API: dataGiornoFinale
        Date dataCorrente = e.getDateStart();
        dataCorrente.toString();
        Calendar cale = Calendar.getInstance();
        cale.setTime(dataCorrente);
        cale.add(Calendar.DATE, +9);
        Date dataGiornoFinale =  cale.getTime();

        String result = "";
        String URL_OpenWeatherMap_weather ="http://api.openweathermap.org/data/2.5/forecast/daily?q="+e.getPlace()+"&cnt=10&mode=json";

        try {
            URL url_weather = new URL(URL_OpenWeatherMap_weather);

            HttpURLConnection httpURLConnection = (HttpURLConnection) url_weather.openConnection();

            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    
                InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader, 8192);
                String line = null;
                while((line = bufferedReader.readLine()) != null){
                    result += line;
                }

                bufferedReader.close();

                JSONObject jsonObject = new JSONObject(result);
                
                long differenzaGiornilong = e.getDateStart().getTime()-today.getTime();
                int giorno = Math.round(differenzaGiornilong/86400000)+1;
                
                JSONArray jsList = jsonObject.getJSONArray("list");
                String citta = jsonObject.getJSONObject("city").getString("name");

                dataCorrente = e.getDateStart();
                i=giorno;
                // dataCorrente += 1;
                dataCorrente.toString();
                Calendar cal = Calendar.getInstance();
                cal.setTime(dataCorrente);
                cal.add(Calendar.DATE, +1);
                Date dataGiorno =  cal.getTime();

                dataCorrente = dataGiorno;
                i++;
                System.out.println("data corrente (giorno dopo evento): "+dataCorrente.toString());
                System.out.println("giorno finale: "+dataGiornoFinale.toString());
                trovato=0;
                
                for(int k=0;k<5;k++){
                    System.out.println("k: "+k);
                    String meteo = jsList.getJSONObject((int)giorno).getJSONArray("weather").getJSONObject(0).getString("main");
                    String meteoDescription = jsList.getJSONObject((int)giorno).getJSONArray("weather").getJSONObject(0).getString("description");
                    int temperatura =(jsList.getJSONObject((int)giorno).getJSONObject("temp").getInt("day")-273);
                   
                    System.out.println("giorno corrente: "+dataCorrente.toString());
                    System.out.println("meteo: "+meteo);
                    
                    if((meteo.equalsIgnoreCase("clear")==true )||(meteo.equalsIgnoreCase("cloud")== true)){
                        return dataCorrente;
                    }

                    // dataCorrente += 1;
                    dataCorrente.toString();
                    cal.setTime(dataCorrente);
                    cal.add(Calendar.DATE, +1);
                    dataGiorno =  cal.getTime();

                    dataCorrente = dataGiorno;
                 
                    giorno++;
                    
                }
                
            }
            else
                System.out.println("un cavolo serachSunny");
        }catch(Exception ex){
            
        }
        
    return dataTrovata;
   }
    public NavigationBean getNavigationBean() {
        return navigationBean;
    }

    public void setNavigationBean(NavigationBean navigationBean) {
        this.navigationBean = navigationBean;
    }
       
}
